<template>
    <view class="container">
        <view class="header">
            <text class="title">TCP 客户端测试</text>
            <text class="status" :class="{'connected': connected, 'disconnected': !connected}">
                {{ connected ? '已连接' : '未连接' }}
            </text>
        </view>
        
        <view class="form-group">
            <view class="form-item">
                <text class="label">服务器 IP:</text>
                <input v-model="ip" placeholder="192.168.1.228" class="input" />
            </view>
            <view class="form-item">
                <text class="label">端口:</text>
                <input v-model.number="port" placeholder="9001" class="input" />
            </view>
            <view class="form-item">
                <text class="label">发送数据:</text>
                <textarea v-model="sendData" placeholder='{"command": "test"}' class="textarea" rows="3"></textarea>
            </view>
        </view>
        
        <view class="button-group">
            <button @click="toggleConnection" class="btn {{ connected ? 'btn-disconnect' : 'btn-connect' }}">
                {{ connected ? '断开连接' : '连接服务器' }}
            </button>
            <button @click="sendDataToServer" class="btn btn-send" :disabled="!connected">
                发送数据
            </button>
        </view>
        
        <view class="log-container">
            <text class="log-title">日志记录:</text>
            <scroll-view scroll-y class="log-scroll">
                <view class="log-list">
                    <text class="log-item" v-for="(log, index) in logs" :key="index">
                        {{ log }}
                    </text>
                </view>
            </scroll-view>
        </view>
        
        <view class="info-panel">
            <view class="info-item">
                <text class="info-label">连接状态:</text>
                <text class="info-value">{{ connected ? '已连接' : '未连接' }}</text>
            </view>
            <view class="info-item">
                <text class="info-label">服务器:</text>
                <text class="info-value">{{ ip }}:{{ port }}</text>
            </view>
            <view class="info-item">
                <text class="info-label">重连尝试:</text>
                <text class="info-value">{{ reconnectAttempts }} / {{ maxReconnectAttempts }}</text>
            </view>
        </view>
    </view>
</template>

<script>
import tcpClient from "@/utils/tcpClientBytesPlugin.js";

export default {
    data() {
        return {
            tcp: null,
            logs: [],
            ip: "192.168.1.228",
            port: 9001,
			// sendData:"{\"request\": \"GetDistortionImage\", \"type\": \"PNG\"}",
           
            sendData: '{"request":"QueryStatus"}',
            pageInstanceId: null
        };
    },
    
    onLoad() {
        this.pageInstanceId = getCurrentPages().pop().$page.id;
        this.initTcpClient();
    },
    
    onShow() {
        if (this.tcp) {
            this.tcp.onPageShow();
        }
    },
    
    onHide() {
        if (this.tcp) {
            this.tcp.onPageHide();
        }
    },
    
    onUnload() {
        if (this.tcp) {
            this.tcp.onPageDestroy();
        }
    },
    
    methods: {
        initTcpClient() {
            this.tcp = tcpClient;
            this.tcp.init(this.pageInstanceId);
            
            // 添加数据接收处理
            this.tcp.addDataHandler((data) => {
                this.addLog(`收到数据: ${JSON.stringify(data)}`);
            });
            
            // 添加连接状态监听
            this.tcp.addDataHandler((status) => {
                this.addLog(`连接状态: ${status}`);
            }, 'connectionEstablished');
            
            this.addLog('TCP 客户端初始化完成');
        },
        
        toggleConnection() {
            if (this.connected) {
                this.disconnect();
            } else {
                this.connect();
            }
        },
        
        connect() {
			
            if (!this.ip || !this.port) {
                this.addLog('请输入服务器 IP 和端口');
                return;
            }
			console.log("connect")
			
			
//             const tcpPlugin = uni.requireNativePlugin('tcpclientbytes');
// tcpPlugin.getJavaVersion()
// 			console.log(tcpPlugin)

// 			tcpPlugin.getJavaVersion((e)=>{
// 				console.log(e)
// 			})
// 			tcpPlugin.initialize((e)=>{
// 				console.log(e)
// 			},err=>{
// 				console.log(err)
// 			}) 
			// tcpPlugin.jsonobj({a:1},(e)=>{
			// 				  console.log(e)
			// })
				console.log("tcpPlugin.testConnection")
				console.log(`尝试连接到 ${this.ip}:${this.port}`);
            // tcpPlugin.testConnection(this.ip, this.port, (result) => {
            // 	this.testResult = "测试结果: " + result;
            // 	console.log("测试结果:", result);
            // });


          this.tcp.connect(this.ip, this.port, 10000); // 10秒超时
        },
        
        disconnect() {
            this.addLog('正在断开连接...');
            this.tcp.close();
        },
        
        sendDataToServer() {
            if (!this.connected) {
                this.addLog('请先连接到服务器');
                return;
            }
            
            try {
                const data = JSON.parse(this.sendData);
                this.tcp.sendData(data);
                this.addLog(`发送数据: ${JSON.stringify(data)}`);
            } catch (error) {
                this.addLog('数据格式错误，请输入有效的 JSON 数据');
                console.error('数据格式错误:', error);
            }
        },
        
        addLog(message) {
            const timestamp = new Date().toLocaleTimeString();
            const log = `${timestamp} - ${message}`;
            this.logs.unshift(log);
            
            // 限制日志数量
            if (this.logs.length > 50) {
                this.logs.pop();
            }
        }
    },
    
    computed: {
        connected() {
            return this.tcp && this.tcp.isConnected();
        },
        reconnectAttempts() {
            return this.tcp ? this.tcp.reconnectAttempts : 0;
        },
        maxReconnectAttempts() {
            return this.tcp ? this.tcp.maxReconnectAttempts : 5;
        }
    }
};
</script>

<style>
.container {
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
}

.title {
    font-size: 36rpx;
    font-weight: bold;
}

.status {
    font-size: 28rpx;
    padding: 8rpx 16rpx;
    border-radius: 30rpx;
}

.connected {
    color: #007AFF;
    border: 1rpx solid #007AFF;
}

.disconnected {
    color: #FF4D4F;
    border: 1rpx solid #FF4D4F;
}

.form-group {
    margin-bottom: 30rpx;
}

.form-item {
    margin-bottom: 20rpx;
}

.label {
    display: block;
    margin-bottom: 10rpx;
    font-size: 28rpx;
    color: #666;
}

.input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
}

.textarea {
    width: 100%;
    height: 200rpx;
    padding: 20rpx;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
    box-sizing: border-box;
}

.button-group {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
}

.btn {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    margin: 0 10rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
}

.btn-connect {
    background-color: #007AFF;
    color: #fff;
}

.btn-disconnect {
    background-color: #FF4D4F;
    color: #fff;
}

.btn-send {
    background-color: #52C41A;
    color: #fff;
}

.log-container {
    flex: 1;
    margin-bottom: 30rpx;
}

.log-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
    color: #333;
}

.log-scroll {
    flex: 1;
    height: 0;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    padding: 10rpx;
    box-sizing: border-box;
}

.log-list {
    display: flex;
    flex-direction: column;
}

.log-item {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 10rpx;
    line-height: 1.5;
}

.info-panel {
    background-color: #f8f8f8;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-top: 20rpx;
}

.info-item {
    display: flex;
    justify-content: space-between;
    padding: 10rpx 0;
    border-bottom: 1rpx solid #eee;
}

.info-item:last-child {
    border-bottom: none;
}

.info-label {
    font-size: 28rpx;
    color: #666;
}

.info-value {
    font-size: 28rpx;
    color: #333;
}
</style>